package com.dy.video.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dy.comments.Comments;
import com.dy.pojo.Goods;
import com.dy.user.User;
import com.dy.video.Gz;
import com.dy.video.service.*;
import com.dy.video.utlis.aliyun.ConstantVodUtils;
import com.dy.video.utlis.aliyun.InitVodCilent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.dy.video.Video;
import com.kaoshi.common.config.Result;


import entity.vo.CommentsVo;
import entity.vo.videoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("video")
@CrossOrigin
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private CommentsService commentsService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    GoodsFeignClient goodsFeignClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    UserFeignClient userFeignClient;

    //上传视频
    @PostMapping("uploadVideos")
    public Result upload(MultipartFile file) throws IOException {
        String videoName = videoService.upload(file);
//        Video video = new Video();
//        video.setVideoName(videoName);
//
        return Result.ok(videoName);
    }

    @PostMapping("publish")
    public Result publish(@RequestBody Video video) {
        Object o = redisTemplate.opsForValue().get("token");
        if (o != null) {
            String token = o.toString().replace("\"", ""); // 去除双引号
            System.out.println("aaaaaaaaaaaa" + token);
            int userByToken = userFeignClient.getUserByToken(token);
            video.setUid(userByToken);
        } else {
            // 处理 token 为空的情况
            throw new RuntimeException("Token not found in Redis");
        }
        videoService.save(video);
        redisTemplate.delete("videoList");

        return Result.ok();
    }

    //查询所有视频
    @GetMapping("findAllVideos")
    public Result findAll() {
        List<videoVo> list = (List<videoVo>) redisTemplate.opsForValue().get("videoList");
        if (list == null) {
            return Result.ok(getfindVideos());
        } else {
            for (videoVo videoVo : list) {

                    if (videoVo.getCampaign() != 0 & videoVo.getImage() == null) {
                        System.out.println(videoVo.getId() + "aaaaaaaaa" + videoVo.getGid());
                        Result goodsDetail = goodsFeignClient.getGoodsDetail(videoVo.getGid());
                        Object data = goodsDetail.getData();
                        if (data instanceof Map) {
                            Map<String, Object> map = (Map<String, Object>) data;
                            if (map == null) {
                                throw new IllegalArgumentException("Map is null");
                            }
                            System.out.println("Map content: " + map);
                            try {
                                Goods goods = objectMapper.convertValue(map, Goods.class);
                                videoVo.setImage(goods.getImg());
                            } catch (Exception e) {
                                e.printStackTrace();
                                throw new RuntimeException("Failed to convert map to Goods object", e);
                            }
                        } else if (data instanceof Goods) {
                            Goods goods = (Goods) data;
                            videoVo.setImage(goods.getImg());
                        } else {
                            throw new IllegalArgumentException("Unexpected data type: " + data.getClass().getName());
                        }
                    }

            }
            return Result.ok(list);
        }
    }


    public List<videoVo> getfindVideos() {
        List<videoVo> videoList = videoService.findAll();
        for (Video video : videoList) {
            String playAuth = getPlayAuth(video.getVideoName());
            video.setVideoName(playAuth);

            Long i = (long) commentsService.tongji(video.getId());
            video.setComnum(i);
        }

        redisTemplate.opsForValue().set("videoList", videoList, 3000, java.util.concurrent.TimeUnit.SECONDS);
        return videoList;
    }


    public String getPlayAuth(String id) {
        try {
            //床架初始化对象
            String vodeid = id;
            // 初始化对象
            DefaultAcsClient defaultAcsClient = InitVodCilent.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);

            // 创建获取对象的request和response
            GetPlayInfoRequest request = new GetPlayInfoRequest();

            //向requst设置视频的id
            request.setVideoId(vodeid);


            request.setEndpoint("vod.cn-beijing.aliyuncs.com");


            // 调用方法得到播放地址
            GetPlayInfoResponse acsResponse = defaultAcsClient.getAcsResponse(request);


            // 获取播放地址列表
            List<GetPlayInfoResponse.PlayInfo> playInfoList = acsResponse.getPlayInfoList();

            // 假设我们只需要第一个播放地址
            String playUrl = null;
            if (playInfoList != null && !playInfoList.isEmpty()) {
                playUrl = playInfoList.get(0).getPlayURL();
            }

            String cleanedUrl = null;
            int dotIndex = playUrl.lastIndexOf(".mp4");
            if (dotIndex != -1) {
                cleanedUrl = playUrl.substring(0, dotIndex + 4); // 包括 .mp4
                System.out.println(cleanedUrl);
            } else {
                System.out.println("未找到 .mp4 结尾的视频地址");
            }

            return cleanedUrl;

        } catch (Exception e) {

            throw new RuntimeException(e.getMessage(), e);
        }
    }

    // 点赞
    @GetMapping("thumbsUptrue")
    public Result thumbsUp(Integer id) {
        Video video = videoService.getById(id);
        if (video == null) {
            return Result.fail("视频不存在");
        }
        video.setThumbsUp(video.getThumbsUp() + 1);
        videoService.updateById(video);
        return Result.ok();
    }

    // 取消点赞
    @GetMapping("thumbsUpfalse")
    public Result thumbsUpfalse(Integer id) {
        Video video = videoService.getById(id);
        if (video == null) {
            return Result.fail("视频不存在");
        }
        video.setThumbsUp(video.getThumbsUp() - 1);
        videoService.updateById(video);
        return Result.ok();
    }

    //主页
    @GetMapping("findByVideo")
    public Result findByVideo(Integer uid) {
        List<videoVo> videoList = videoService.findByVideo(uid);
        for (Video video : videoList) {
            String playAuth = getPlayAuth(video.getVideoName());
            video.setVideoName(playAuth);
        }
        return Result.ok(videoList);
    }


    @PostMapping("pl")
    public Result pl(@RequestBody Comments comments) {
        if (comments.getComment() == null) {
            return Result.fail("评论不能为空");
        }
        commentsService.save(comments);
        videoService.updateByComnum(comments.getVid());
        return Result.ok();
    }

    @GetMapping("commentAll/{id}")
    public Result commentAll(@PathVariable Integer id) {
        List<CommentsVo> commentsVoList = commentsService.commentAll(id);
        return Result.ok(commentsVoList);
    }

    @Autowired
    GzService gzService;


    //关注
    @GetMapping("attention")
    public Result attention(Integer uid, Integer userid) {
        Gz gz = new Gz();
        gz.setUid(uid);
        gz.setUserUid(userid);


        gzService.attention(gz);
        return Result.ok();
    }

    //取消关注
    @GetMapping("qxgz")
    public Result qxgz(Integer uid, Integer userid) {
        LambdaQueryWrapper<Gz> qr = new LambdaQueryWrapper<Gz>();
        qr.eq(Gz::getUid, userid);
        qr.eq(Gz::getUserUid, uid);
        gzService.remove(qr);
        return Result.ok();
    }

    //判断是否关注
    @GetMapping("getGZ")
    public Result getGZ(Integer uid, Integer userid) {
        List<Gz> list = gzService.list();
        for (Gz gz : list) {
            if (gz.getUid() == uid && gz.getUserUid() == userid) {
                return Result.ok();
            }
        }
        return Result.fail();
    }

    @GetMapping("getFans")
    public Result getFans(Integer uid) {
        LambdaQueryWrapper<Gz> qr = new LambdaQueryWrapper<>();
        qr.eq(Gz::getUid, uid);
        List<Gz> list = gzService.list(qr);
        List<User> userList = new ArrayList<>();
        for (Gz gz : list) {
            User user = userFeignClient.getUserById(gz.getUserUid());
            userList.add(user);
        }
        return Result.ok(userList);
    }

    @GetMapping("getGuan")
    public Result getGuan(Integer uid) {
        LambdaQueryWrapper<Gz> qr = new LambdaQueryWrapper<>();
        qr.eq(Gz::getUid, uid);
        List<Gz> list = gzService.list(qr);
        List<User> userList = new ArrayList<>();
        for (Gz gz : list) {
            User user = userFeignClient.getUserById(gz.getUserUid());
            userList.add(user);
        }
        return Result.ok(userList);
    }

    @GetMapping("getUser")
    public Result getUser(Integer uid) {
        User user = userFeignClient.getUserById(uid);
        return Result.ok(user);
    }

    //查询关注的视频和用户
    @PostMapping("findAllVideos1")
    public Result findAll1(@RequestBody Video v) {
        List<videoVo> videoList = videoService.findAll1(v);
        for (Video video : videoList) {
            String playAuth = getPlayAuth(video.getVideoName());
            video.setVideoName(playAuth);
        }
        return Result.ok(videoList);
    }

    //查询朋友的视频和用户
    @GetMapping("findAllVideos2")
    public Result findAll2() {
        List<videoVo> videoList = videoService.findAll2();
        for (Video video : videoList) {
            String playAuth = getPlayAuth(video.getVideoName());
            video.setVideoName(playAuth);
        }
        return Result.ok(videoList);
    }


    @RequestMapping("findList")
    public Result findList(Video video) {
        List<Video> videoList = videoService.findList(video);
        return Result.ok(videoList);
    }


}
